# ecoding:utf-8
import os
from PIL import Image
import piexif
import win32con
import win32ui
import ctypes
import numpy as np
import re

"""
安装第三方包
https://blog.csdn.net/qq_16047709/article/details/125521944
https://blog.csdn.net/m0_56729804/article/details/135416674
pip install numpy  数组的库
pip install piexif
pip install pywin32
pip install Pillow
pip install pyinstaller
打包命令：pyinstaller -F -i .\gps.ico .\gps.py
"""

# DIP缩放设置
awareness = ctypes.c_int()
errorCode = ctypes.windll.shcore.GetProcessDpiAwareness(0, ctypes.byref(awareness))
errorCode = ctypes.windll.shcore.SetProcessDpiAwareness(2)
success = ctypes.windll.user32.SetProcessDPIAware()


def fileNameInfoArray(fileName: str):
    result = []
    fileName.split(',')
    return result


# https: // blog.csdn.net / qq_41813454 / article / details / 136272149
def traverse_folder(folder_path):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            abs_file_path = os.path.join(root, file)
            print(abs_file_path)
            # file_name, file_extension = os.path.splitext(file)
            # file_extension = file_extension[1:]  # 去掉点号
            # print("去掉点号的扩展名:", file_extension)  # 输出: 去掉点号的扩展名: txt
            # print("文件名:", file_name)  # 输出: 文件名: /home/user/documents/example
            # print("扩展名:", file_extension)  # 输出: 扩展名: .txt
            process_img(abs_file_path)


def main():
    # image_path = browse(True)[1]
    # gps_str = input('请输入经纬度：')
    # arr = gps_str.split(',')
    # lng = float(arr[1])
    # lat = float(arr[0])
    print("开始执行")
    image_dir = 'E:\\test\\img'
    traverse_folder(image_dir)


def process_img(abs_file_path):
    # pathlike_object = os.fspath(abs_file_path)
    # file_obj = open(abs_file_path)
    # file_obj.close()
    file_all_name = os.path.basename(abs_file_path)
    file_name, file_extension = os.path.splitext(file_all_name)
    file_extension = file_extension[1:]  # 去掉点号
    print("去掉点号的扩展名:", file_extension)  # 输出: 去掉点号的扩展名: txt
    print("文件名:", file_name)  # 输出: 文件名: /home/user/documents/example
    print("扩展名:", file_extension)  # 输出: 扩展名: .txt

    #照片名称格式 2024-06-01       094853   30.20120,  18.566000000.jpg
    new_file_name = re.sub(r"\s+", " ",
                           file_name)  # 使用正则表达式将字符串中的多个空格合成一个空格：如 "Python    将    多个空格   合成   一个" ---》 "Python 将 多个空格 合成 一个"
    print(new_file_name)

    info_1, grs_2 = new_file_name.split(',')
    date, time, grs_1 = info_1.strip().split(' ')
    date = date.replace('-', ':')
    # date = '2021:06:01' 日期格式必须要这样
    hour = time[:2]
    minute = time[2:4]
    second = time[4:]
    print("date:", date)
    print("time:", time)
    print("hour:", hour)
    print("minute:", minute)
    print("second:", second)
    print("grs_1:", grs_1)
    print("grs_2:", grs_2)

    image_path = abs_file_path
    lng = float(grs_1) #字符串转double 34.2653811
    lat = float(grs_2) #字符串转double 182.65333
    # 将经纬度与相对航高转为exif可用的经纬度与行高
    # exif需要的航高输入为(20000,2)格式，表示高度为20000/100米
    # exif需要的经度与维度为((12, 1), (20,1), (41000, 1000))格式表示12度20分41秒
    lng_exif = format_latlng(lng)
    lat_exif = format_latlng(lat)
    _dict = {"lng": lng_exif, "lat": lat_exif, "lng_ref": 'E', "lat_ref": 'N',
             'dateTimeOriginal': date +' '+ hour + ':' + minute + ':' + second}
    print("写入文件：", image_path)
    # 判断图片是否有exif
    read_check_exif(image_path)
    # 修改图片的exif
    read_modify_exif(image_path, _dict)


def browse(mode: bool,
           default_name: str = "",
           title: str = "选择您的文件",
           file_type: str = "图片文件(*.jpg)|*.jpg|",
           path: str = "desktop"):
    """弹出窗口返回保存或者选择的路径
    :param mode: False"为 "保存/另存为", "True"为 "打开"
    :param default_name:默认输入文件名
    :param title:窗口提示
    :param file_type:可选的文件类型,所有文件(*.*)|*.*|图片文件(*.jpg)|*.jpg|
    :param path:
    :return:[存储类型、文件路径、文件类型]
    """
    api_flag = win32con.OFN_OVERWRITEPROMPT | win32con.OFN_FILEMUSTEXIST
    dlg = win32ui.CreateFileDialog(mode, None, default_name, api_flag, file_type)
    dlg.SetOFNTitle(title)
    dlg.SetOFNInitialDir(os.path.abspath(path))
    dlg.DoModal()
    filename = dlg.GetPathName()
    fileExt = dlg.GetFileExt()
    if os.path.exists(filename):
        if_pass = True
    elif not mode:
        if os.path.split(filename)[0] == '':
            if_pass = False
        else:
            if_pass = True
    else:
        if_pass = False
    return [if_pass, filename, fileExt]


def format_latlng(latlng):
    """经纬度十进制转为分秒"""
    degree = int(latlng)
    res_degree = latlng - degree
    minute = int(res_degree * 60)
    res_minute = res_degree * 60 - minute
    seconds = round(res_minute * 60.0, 3)

    return ((degree, 1), (minute, 1), (int(seconds * 1000), 1000))


def read_check_exif(image_path):
    """
    判断图片是否有'exif'信息,没有就写入初始'exif'信息
    :param image_path:图片路径
    :return:无
    """
    img = Image.open(image_path)  # 读图
    try:
        exif_dict = piexif.load(img.info['exif'])  # 提取exif信息
    except KeyError:
        # 处理exif不存在的情况
        # 创建一个初始的EXIF字典
        exif_dict = {"0th": {}, "Exif": {}, "GPS": {}, "Interop": {}, "1st": {}, "thumbnail": None}
        # 将EXIF字典添加到图像的元数据中
        exif_bytes = piexif.dump(exif_dict)
        img.save(image_path, exif=exif_bytes)


def read_modify_exif(image_path, _dict):
    """ 读取并且修改exif文件"""
    img = Image.open(image_path)  # 读图
    exif_dict = piexif.load(img.info['exif'])  # 提取exif信息

    exif_dict['Exif'][piexif.ExifIFD.DateTimeOriginal] = _dict['dateTimeOriginal']  # 修改拍摄日期
    exif_dict['GPS'][piexif.GPSIFD.GPSLongitude] = _dict['lng']  # 修改经度
    exif_dict['GPS'][piexif.GPSIFD.GPSLatitude] = _dict['lat']  # 修改纬度
    exif_dict['GPS'][piexif.GPSIFD.GPSLongitudeRef] = _dict['lng_ref']  # odm需要读取，一般为’W'
    exif_dict['GPS'][piexif.GPSIFD.GPSLatitudeRef] = _dict['lat_ref']  # 一般为‘N'

    exif_bytes = piexif.dump(exif_dict)
    piexif.insert(exif_bytes, image_path)


if __name__ == "__main__":
    main()
